package com.lqian.time.localdate;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 解决方案3：使用ThreadLocal方式
 * 使用ThreadLocal保证每一个线程有SimpleDateFormat对象副本。这样就能保证线程的安全。
 * 使用ThreadLocal能保证线程安全，且效率也是挺高的。适合高并发场景使用。
 */
public class SimpleDateFormatTest4 {
    private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>(){
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };


    public static void main(String[] args) throws ParseException {
        //1.创建线程池
        ExecutorService pool = Executors.newFixedThreadPool(10);
        //2.为线程池分配任务
        ThreadPoolTest task = new ThreadPoolTest();
        for (int i = 0; i <10 ; i++) {
            pool.submit(task);
        }
        //3.关闭线程
        pool.shutdown();
        }

    static class ThreadPoolTest implements Runnable{

        @Override
        public void run() {
            String dateString1 = threadLocal.get().format(new Date());
            try {
                Date date = threadLocal.get().parse(dateString1);
                String dateString2 = threadLocal.get().format(date);
                System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString1.equals(dateString2));
            } catch (Exception e) {
                System.out.println(Thread.currentThread().getName()+" 格式化失败 ");
            }

        }
    }


}
